package cc.telecomdigital.tdstock.activity.groups.more.push.util;

import android.content.Context;
import android.os.AsyncTask;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;

public class NotificationProfile
{
	private final static String		TAG		= NotificationProfile.class
												.getSimpleName();
	private static NotificationProfile	instance	= null;

	private NotificationProfile()
	{
	}

	public synchronized static NotificationProfile getInstace()
	{
		if (instance == null)
		{
			instance = new NotificationProfile();
			init();
		}

		return instance;
	}

	private static void init()
	{

	}

	public void onUpdatePushServer(Context context, String pushServer)
	{
		if (null != context)
		{
			new UpdatePushServerTask(context).execute(pushServer);
		}

	}

	class UpdatePushServerTask extends AsyncTask<String, Void, String[]>
	{
		private Context	context;
		private int		retryTimes	= 0;
		private final long	retryLimit	= 20 * 1000;

		public UpdatePushServerTask(Context context)
		{
			this.context = context;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected String[] doInBackground(String... params)
		{
			if (params.length < 1)
			{
				TDStockLog.e(TAG,
						" doInBackground in UpdatePushServerTask need one or more param!");
				return null;
			}

			String response = getContent(params[0].trim());
			TDStockLog.d(TAG, null == response ? "" : response);

			return null;
		}

		@Override
		protected void onPostExecute(String[] result)
		{
			// don't put the code here for it block the user's action
			super.onPostExecute(result);
		}

		public String getContent(String host)
		{
			String tmpContent = null;

			String profileUrl = Data.getUpdatePushServerProfileURL(context,
					host);
			TDStockLog.d(TAG, "profileUrl:" + profileUrl);

			if (SystemInfo.isNetworkingConnected(context))
			{
				tmpContent = /* DataRead.getContentFromURL(url); */DataRead
						.getContentFromURL(profileUrl);
			}

			long startTime = System.currentTimeMillis();

			retryTimes = 0;
			while (tmpContent == null
					&& (System.currentTimeMillis() - startTime <= retryLimit))
			{
				if (!SystemInfo.isNetworkingConnected(context))
				{
					TDStockLog.d(TAG, "检测到没有网络, 正在准备重试:当前重试次数:"
							+ retryTimes++);
					Thread.yield();
					continue;
				}
				else
				{
					profileUrl = Data.getUpdatePushServerProfileURL(
							context, host);
					TDStockLog.d(TAG, "profileUrl:" + profileUrl);
					TDStockLog.d(TAG, "检测到有网络了, 正在准备重试:当前重试次数:"
							+ retryTimes++);
					tmpContent = /* DataRead.getContentFromURL(url); */DataRead
							.getContentFromURL(profileUrl);
					TDStockLog.d(TAG, "重试结果:" + tmpContent == null ? "失败!"
							: "成功!");
				}

			}

			return tmpContent;

		}
	}

}